#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import os
import platform
import random
import sys
import time

from colorama import init
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

from day import *

init(autoreset=True)


# 执行命令
def shell(s):
    print(">", s)
    return os.popen(s).read().strip()

def mac_now_wifi(device):
    current = shell("networksetup -getairportnetwork {}|awk -v FS=': ' '{{print $2}}'".format(device))
    print("Now Wi-Fi: {}".format(current))
    return current


def mac_switch_wifi(name):
    if name and platform.system() == 'Darwin':
        device = shell("networksetup -listallhardwareports|grep 'Hardware Port: Wi-Fi' -A1|grep 'Device:'|awk -v FS=': ' '{print $2}'")
        print("Wi-Fi Device: {}".format(device))
        current = mac_now_wifi(device)
        if current != name:
            shell("networksetup -setairportnetwork {} {}".format(device, name))
            print("Switched To: {}".format(name))
            mac_now_wifi(device)
        return current


def got_user():
    print(sys.argv)
    usr = 'zyliu'
    pwd = 'Lyjwkhhbj99'
    force = False
    fast = False
    if len(sys.argv) > 1:
        if sys.argv[1] == '1':
            force = True
        else:
            usr = sys.argv[1]
    if len(sys.argv) > 2:
        pwd = sys.argv[2]
    if len(sys.argv) > 3 and sys.argv[3] == '1':
        force = True
    return {'usr': usr, 'pwd': pwd, 'force': force}


def color(flag, s1, s2):
    if flag:
        return "\033[1;32m" + s1 + "\033[0m"  # 绿
    else:
        return "\033[1;31m" + s2 + "\033[0m"  # 红


def wait(n):
    print("等待" + str(n) + "秒")
    time.sleep(n)


def rd_wait():
    wait(random.randint(2, 5))


def open_chrome(url):
    print("## 打开", url)
    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
    prefs = {
        'profile.default_content_setting_values': {
            'images': 2,
            'notification': 2,
        }
    }
    chrome_options.add_experimental_option('prefs', prefs)
    chrome_options.add_argument('lang=zh_CN.UTF-8')
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--start-maximized')
    chrome_options.add_argument('--disable-dev-shm-usage')
    chrome_options.add_argument('--disable-popup-blocking')
    chrome_options.add_argument('--disable-java')
    chrome_options.add_argument('--disable-plugins')
    chrome_options.add_argument('--disable-images')
    chrome_options.add_argument('--disable-infobars')
    chrome_options.add_argument('--headless')
    driver = webdriver.Chrome(options=chrome_options)
    driver.get(url)
    return driver


def user_login(user):
    driver = open_chrome("http://172.25.22.209:8080/seeyon/main.do?method=index")
    print("## 登陆", driver.current_url)
    driver.find_element(By.ID, "login_username").click()
    driver.find_element(By.ID, "login_username").clear()
    driver.find_element(By.ID, "login_username").send_keys(user['usr'])
    driver.find_element(By.ID, "login_password1").clear()
    driver.find_element(By.ID, "login_password1").send_keys(user['pwd'])
    driver.find_element(By.ID, "login_button").click()
    return driver


def cookie_check(driver):
    kv = []
    for cookie in driver.get_cookies():
        kv.append(cookie['name'] + "=" + cookie['value'])
    if len(kv) < 3:
        print("登陆失败！")
        driver.quit()
        sys.exit(1)
    return "; ".join(kv)


def got_now_time():
    dt = time.localtime()
    return time.strftime('%Y-%m-%d %H:%M:%S', dt)


def now_is_before_9h(now):
    dt1 = time.strptime(now, '%Y-%m-%d %H:%M:%S')
    dt = now.split(' ')[0]
    dt2 = time.strptime(dt + ' 09:00:00', '%Y-%m-%d %H:%M:%S')
    return dt1 < dt2


def now_is_after_18h(now):
    dt1 = time.strptime(now, '%Y-%m-%d %H:%M:%S')
    dt = now.split(' ')[0]
    dt2 = time.strptime(dt + ' 18:00:00', '%Y-%m-%d %H:%M:%S')
    return dt1 > dt2


def got_his_array(driver):
    wait(1)
    print("## 已发事项")
    WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.ID, "titleName_6008457975895703560")))  # 检查页面存在某元素，元素不一定可见
    driver.find_element(By.ID, "titleName_6008457975895703560").click()
    wait(1)
    tbody = driver.find_element(By.XPATH, "//div[@id='panelBody_-7962961068184354312']/div/div[1]/table/tbody")
    trs = tbody.find_elements(By.TAG_NAME, "tr")
    his = []
    for i in range(len(trs)):
        c1 = driver.find_element(By.XPATH, "//div[@id='panelBody_-7962961068184354312']/div/div[1]/table/tbody/tr[" + str(i + 1) + "]/td[1]/div/span/span[2]").text
        c2 = driver.find_element(By.XPATH, "//div[@id='panelBody_-7962961068184354312']/div/div[1]/table/tbody/tr[" + str(i + 1) + "]/td[2]/span/span").text
        his.append(c2 + c1)
        print(his[i])
    return his


def is_signin(his):
    for i in range(len(his)):
        if "今日" in his[i] and "考勤签到" in his[i]:
            return True
    return False


def is_signout(his):
    for i in range(len(his)):
        if "今日" in his[i] and "考勤签退" in his[i]:
            return True
    return False


def is_signlog(his):
    for i in range(len(his)):
        if "今日" in his[i] and "日志填写" in his[i]:
            return True
    return False


def got_my_template(driver):
    tds = driver.find_elements(By.CLASS_NAME, "padding_r_10")
    tmps = []
    for i in range(len(tds)):
        a = tds[i].find_element(By.TAG_NAME, "a")
        templateId = a.get_attribute("onclick").split("templateId=")[1].split("','")[0]
        tmps.append(a.text + "(" + templateId + ")")
        if a.text == '考勤签到':
            signin = templateId
        elif a.text == '考勤签退':
            signout = templateId
        elif a.text == '外包日志填写':
            signlog = templateId
    print(" ".join(tmps))
    return {'len': len(tds), 'signin': signin, 'signout': signout, 'signlog': signlog}


def to_frist_table(driver):
    print("切换到第一个标签", driver.current_window_handle)
    driver.switch_to.window(driver.window_handles[0])
    rd_wait()
    print("切换后", driver.current_window_handle)


def to_new_table(driver, url):
    print("打开新标签", driver.current_window_handle)
    driver.execute_script("window.open('" + url + "', '_blank')")
    rd_wait()
    print("切换到新标签", driver.current_window_handle)
    driver.switch_to.window(driver.window_handles[-1])
    print("切换到新标签后", driver.current_window_handle)
    rd_wait()


def do_signin(driver, templateId):
    print("## 签到")
    to_new_table(driver, "http://172.25.22.209:8080/seeyon/collaboration/collaboration.do?method=newColl&from=templateNewColl&templateId=" + templateId);
    rd_wait()
    print("提交表单")
    driver.find_element(By.ID, "sendId_span").click()
    to_frist_table(driver)


def do_signout(driver, templateId):
    print("## 签退")
    to_new_table(driver, "http://172.25.22.209:8080/seeyon/collaboration/collaboration.do?method=newColl&from=templateNewColl&templateId=" + templateId);
    rd_wait()
    print("提交表单")
    driver.find_element(By.ID, "sendId_span").click()
    to_frist_table(driver)


def do_signlog(driver, templateId, txt1, txt2, txt3):
    rd_wait()
    print("## 写日志", txt1, txt2, txt3)
    to_new_table(driver, "http://172.25.22.209:8080/seeyon/collaboration/collaboration.do?method=newColl&from=templateNewColl&templateId=" + templateId);
    print("进入iFrame")
    rd_wait()
    driver.switch_to.frame("zwIframe")
    print("填输入框")
    inputs = driver.find_elements(By.TAG_NAME, "input")
    print(inputs)
    inputs[2].click()
    inputs[2].clear()
    inputs[2].send_keys(txt1)
    inputs[4].click()
    inputs[4].clear()
    inputs[4].send_keys(txt2)
    print("填文本域")
    textareas = driver.find_elements(By.TAG_NAME, "textarea")
    textareas[0].click()
    textareas[0].clear()
    textareas[0].send_keys(txt3)
    print("退出iFrame切到主文档")
    driver.switch_to.default_content()
    rd_wait()
    print("提交表单")
    driver.find_element(By.ID, "sendId_span").click()
    to_frist_table(driver)


def user_logout(driver):
    print("## 退出登陆")
    driver.find_element(By.XPATH, "//div[@id='topRightsystemOperationWidth']/ul/li[7]/i").click()
    driver.find_element(By.ID, "logout").click()
    driver.find_element(By.LINK_TEXT, "确定").click()


def is_work_day(nowTime):
    t = nowTime.split(' ')[0]
    f = 'bd.json'
    if os.path.exists(f):
        with open(f, 'r') as f:
            j = json.load(f)
            return j[t] == 2
    else:
        return bd[t] == 2
